<template>
   <div class="app-container">
      <div class="p4">
         <FaSearchBar :show-toggle="false">
            <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
               <el-form-item label="部门名称" prop="deptName">
                  <el-input v-model="queryParams.deptName" placeholder="请输入部门名称" clearable style="width: 150px"
                     @keyup.enter="handleQuery" />
               </el-form-item>
               <el-form-item label="状态" prop="status">
                  <el-select v-model="queryParams.status" placeholder="部门状态" clearable style="width: 150px">
                     <el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                  </el-select>
               </el-form-item>
               <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button @click="resetQuery">重置</el-button>
               </el-form-item>
            </el-form>
         </FaSearchBar>
         <el-divider border-style="dashed" style="margin:0px 0px 20px 0px" />

         <el-space wrap>
            <el-button type="primary" icon="Plus" @click="handleAdd" v-auth="['system:dept$add']">新增</el-button>
         </el-space>
         <el-table v-loading="loading" :data="deptList" row-key="id" ref="tableRef" lazy :load="loadChildren"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" stripe highlight-current-row border
            class="mt4">
            <el-table-column prop="deptName" label="部门名称"></el-table-column>
            <el-table-column prop="deptType" label="类型">
               <template #default="scope">
                  <DictTag :dictData="sys_dept_type" :value="scope.row.deptType" />
               </template>
            </el-table-column>
            <el-table-column prop="sort" label="顺序"></el-table-column>
            <el-table-column prop="status" label="状态">
               <template #default="scope">
                  <DictTag :dictData="sys_common_status" :value="scope.row.status" />
               </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createdAt" width="200">
               <template #default="scope">
                  <span>{{ parseTime(scope.row.createdAt) }}</span>
               </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="280px" class-name="small-padding fixed-width">
               <template #default="scope">
                  <el-button size="small" plain type="primary" icon="Plus" @click="handleAdd(scope.row)"
                     v-auth="['system:dept$add']">新增
                  </el-button>
                  <el-button size="small" plain type="success" icon="Edit" @click="handleUpdate(scope.row)"
                     v-auth="['system:dept$edit']">修改
                  </el-button>
                  <el-button size="small" plain type="danger" icon="Delete" @click="handleDelete(scope.row)"
                     v-auth="['system:dept$remove']">删除
                  </el-button>
               </template>
            </el-table-column>
         </el-table>
      </div>
      <!-- 添加或修改部门对话框 -->
      <el-dialog :title="title" v-model="open" width="600px" append-to-body>
         <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
            <el-row>
               <el-col :span="24" v-if="form.parentId !== 0">
                  <el-form-item label="上级部门" prop="parentId">
                     <el-tree-select v-model="form.parentId" :data="deptOptions"
                        :props="{ value: 'id', label: 'deptName', children: 'children' }" value-key="id"
                        placeholder="选择上级部门" check-strictly />
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="类型" prop="deptType">
                     <el-radio-group v-model="form.deptType">
                        <el-radio v-for="dict in sys_dept_type" :key="dict.value" :label="dict.value">{{ dict.label
                           }}</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="部门名称" prop="deptName">
                     <el-input v-model="form.deptName" placeholder="请输入部门名称" />
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="顺序" prop="sort">
                     <el-input-number v-model="form.sort" controls-position="right" :min="0" />
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="负责人" prop="leader">
                     <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="联系电话" prop="phone">
                     <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="邮箱" prop="email">
                     <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="状态">
                     <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_common_status" :key="dict.value" :label="Number(dict.value)">{{ dict.label
                           }}</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Dept">
import apiDept from "@/api/system/dept";

import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const { sys_common_status, sys_dept_type } = proxy.useDict("sys_common_status", "sys_dept_type");

const deptList = ref([]);
const open = ref(false);
const loading = ref(false);
const title = ref("");
const deptOptions = ref([]);

const tableRef = ref();
const maps = new Map();

const data = reactive({
   form: { parentId: "0" },
   queryParams: {
      deptName: undefined,
      status: undefined,
      parentId: "0"
   },
   rules: {
      //  parentId: [{ required: true, message: "上级部门不允许为空", trigger: "blur" }],
      deptName: [{ required: true, message: "部门名称不允许为空", trigger: "blur" }],
      deptType: [{ required: true, message: "类型不允许为空", trigger: "blur" }],
      sort: [{ required: true, message: "顺序不允许为空", trigger: "blur" }],
      email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
      phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
   },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询部门列表 */
function getList() {
   // loading.value = true
   queryParams.value.parentId = "0"
   apiDept.childrenDept(queryParams.value).then(response => {
      deptList.value = proxy.handleTree(response.data, "id");
   }).finally(() => {
      loading.value = false
   })
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
/** 表单重置 */
function reset() {
   form.value = {
      id: undefined,
      parentId: undefined,
      deptName: undefined,
      sort: 0,
      deptType: undefined,
      leader: undefined,
      phone: undefined,
      email: undefined,
      status: "0"
   };
   proxy.resetForm("deptRef");
}
/** 搜索按钮操作 */
function handleQuery() {
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
   reset();
   apiDept.list().then(response => {
      deptOptions.value = proxy.handleTree(response.data, "id");
   });
   if (row != undefined) {
      form.value.parentId = row.id;
   }
   open.value = true;
   title.value = "添加部门";
}
/** 修改按钮操作 */
function handleUpdate(row) {
   reset();
   apiDept.listDeptExcludeChild(row.id).then(response => {
      deptOptions.value = proxy.handleTree(response.data, "id");
   });
   apiDept.getById(row.id).then(response => {
      form.value = response.data;
      form.value.deptType = response.data.deptType + ''
      if (response.data.parentId == 0) {
         form.value.parentId = null
      }
      open.value = true;
      title.value = "修改部门";
   });
}
/** 提交按钮 */
function submitForm() {
   proxy.$refs["deptRef"].validate(valid => {
      if (valid) {
         if (form.value.parentId === null) {
            form.value.parentId = "0"
         }
         if (form.value.id != undefined) {
            apiDept.update(form.value).then(response => {
               proxy.$modal.success("修改成功");
               open.value = false;
               let r = { ...form.value }
               refreshChildren(r.parentId)
            });
         } else {
            apiDept.add(form.value).then(response => {
               proxy.$modal.success("新增成功");
               open.value = false;
               let r = { ...form.value }
               addNode(tableRef.value.data, r.parentId)
               refreshChildren(r.parentId)
            });
         }
      }
   });
}
/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?').then(function () {
      return apiDept.delete(row.id);
   }).then(() => {
      deleteNode(deptList.value, row.id)
      proxy.$modal.success("删除成功");
   }).catch(() => { });
}

// 懒加载子节点方法
const loadChildren = async (row, treeNode, resolve) => {
   row.loading = true
   maps.set(row.id, { row, treeNode, resolve })
   apiDept.childrenDept({ parentId: row.id }).then(response => {
      updateTree(tableRef.value.data, row.id, response.data)
      resolve(response.data)
   }).catch((error) => {
      console.error('加载失败:', error)
      resolve([])
   }).finally(() => {
      setTimeout(() => row.loading = false, 500)
   })
}

const refreshChildren = (parentId) => {
   if (!parentId || parentId == '0') {
      getList()
   } else {
      const map = maps.get(parentId);
      if (map) {
         loadChildren(map.row, map.treeNode, map.resolve)
      }
   }
}
const addNode = (data, targetId) => {
   for (let i = 0; i < data.length; i++) {
      if (data[i].id === targetId) {
         data[i].hasChildren = true
         tableRef.value.toggleRowExpansion(data[i], false)
         nextTick(() => {
            tableRef.value.toggleRowExpansion(data[i], true)
         })
      }
      if (data[i].children && data[i].children.length > 0) {
         addNode(data[i].children, targetId);
      }
   }
   return false
}
// 更新完整数据树
const updateTree = (tree, targetId, newChildren) => {
   for (const node of tree) {
      if (node.id === targetId) {
         node.children = newChildren
         return true
      }
      if (node.children) {
         if (updateTree(node.children, targetId, newChildren)) return true
      }
   }
   return false
}

// 执行删除
const deleteNode = (data, targetId) => {
   for (let i = 0; i < data.length; i++) {
      if (data[i].id === targetId) {
         data.splice(i, 1)
         return true
      }
      if (data[i].children && data[i].children.length > 0) {
         if (deleteNode(data[i].children, targetId)) {
            return true
         }
      }
   }
   return false
}

getList();
</script>
